package thread.syn;

import org.junit.runner.notification.StoppedByUserException;

import javax.sound.midi.Soundbank;

/**
 * Created by 4790K_NSL on 2017/4/18.
 */
public class TraditionThreadSynchronized {

    static public  void  main(String[] args){
      TraditionThreadSynchronized a=new TraditionThreadSynchronized();
        a.init();
    }

    public void init(){
        final Outputer outputer =new Outputer();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    outputer.output("ning shao lin");
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    outputer.output("dai jing jia");
                   // outputer.output1("daijingjia");该代码也可以互斥,因为使用的是同一个锁
                }
            }
        }).start();
    }

    class  Outputer {
        public void output(String string){
            int len=string.length();
            synchronized (this){
                //this 为锁,同步的时候必须使用同一个锁
                for(int i=0;i<len;i++){
                    System.out.print(string.charAt(i));
                }
                System.out.println();
            }

        }

        public synchronized void output1(String string){
            int len=string.length();
            synchronized (this){
                //this 为锁,同步的时候必须使用同一个锁
                for(int i=0;i<len;i++){
                    System.out.print(string.charAt(i));
                }
                System.out.println();
            }

        }
    }
}
